<template>
  <!--下方查看详情表格面板-->
  <div v-if="showTable" class="new-queryResultDiv" :class="showSelectId?'min-Table':'max-Table'">
    <div class="new-queryTableBtn">
      <el-button @click="closeTableDiv" type="primary">关闭</el-button>
      <el-button v-if="isManage" @click="deleteSelectData" type="primary">删除</el-button>
      <span class="new-queryTableSpan">{{ selectType }}</span>
    </div>
    <div class="new-queryTableDiv">
      <!--数据表格-->
      <el-form ref="formTable" :model="tableDataForm" style="height:100%;">
        <el-table v-loading="loading" ref="multipleTable"
                  :data="tableDataForm.tableData" tooltip-effect="dark" height="100%" @selection-change="handleSelectionChange" stripe
                  :header-cell-style="{textAlign:'center'}" :cell-style="{textAlign:'center'}">
          <el-table-column v-if="isManage" type="selection" width="50"> </el-table-column>
          <el-table-column label="序号" width="55" type="index" align="center">
            <template #default="scope">
              <span>{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <!--重大工程历史震害czt_major_project-->
          <template v-if="selectType=='重大工程历史震害'">
            <!-- <el-table-column property="cmpId" label="id"></el-table-column>-->
            <el-table-column v-for="(item, index) in tableColumns1" :key="'type1.' + index + '.'+item.filedProp" :width="160"
                             :prop="item.filedProp" :label="item.filedName">
              <template #default="scope">
                <span v-if="!scope.row.isEdit">
                  {{ scope.row.dictItemNameObj[item.filedProp] }}
                </span>
                <el-form-item v-else :prop="'tableData.' + scope.$index + '.' + item.filedProp" :rules="tableDataForm.rules1[item.filedProp]">
                  <el-select v-if="item.filedType=='select'" v-model="scope.row[item.filedProp]" @change="(value) => onChangeSelect(value,item.filedProp,scope.row)"
                             :disabled="item.readonly=='readonly'" placeholder="请选择" clearable>
                    <el-option v-for="item in getDictArray(scope.row,item.filedProp,item.filedName,selectType)" :key="item.code" :label="item.name"
                               :value="item.code">
                    </el-option>
                  </el-select>
                  <el-date-picker v-else-if="item.filedType=='data'" v-model="scope.row[item.filedProp]"
                                  type="data" value-format="YYYY-MM-DD" placeholder="请选择">
                  </el-date-picker>
                  <el-time-picker
                    v-else-if="item.filedType=='time'"
                    v-model="scope.row[item.filedProp]"
                    value-format="HH:mm:ss"
                    placeholder="请选择"
                  />
                  <el-input v-else-if="item.readonly=='readonly'" v-model.trim="scope.row.dictItemNameObj[item.filedProp]" :disabled="item.readonly=='readonly'"></el-input>
                  <el-input v-else v-model.trim="scope.row[item.filedProp]"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </template>
          <!--水库大坝czt_reservior-->
          <template v-if="selectType=='水库大坝'">
            <!--<el-table-column property="crId" label="id"></el-table-column>-->
            <el-table-column v-for="(item, index) in tableColumns2" :key="'type2.' + index + '.'+item.filedProp" :width="160"
                             :prop="item.filedProp" :label="item.filedName">
              <template #default="scope">
                <span v-if="!scope.row.isEdit">
                  {{ scope.row.dictItemNameObj[item.filedProp] }}
                </span>
                <el-form-item v-else :prop="'tableData.' + scope.$index + '.' + item.filedProp" :rules="tableDataForm.rules2[item.filedProp]">
                  <el-select v-if="item.filedType=='select'" v-model="scope.row[item.filedProp]" @change="(value) => onChangeSelect(value,item.filedProp,scope.row)"
                             :disabled="item.readonly=='readonly'" placeholder="请选择" clearable>
                    <el-option v-for="item in getDictArray(scope.row,item.filedProp,item.filedName,selectType)" :key="item.code" :label="item.name"
                               :value="item.code">
                    </el-option>
                  </el-select>
                  <el-input v-else-if="item.readonly=='readonly'" v-model.trim="scope.row.dictItemNameObj[item.filedProp]" :disabled="item.readonly=='readonly'"></el-input>
                  <el-input v-else v-model.trim="scope.row[item.filedProp]"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </template>
          <!--燃气-储气罐czt_air_receiver-->
          <template v-if="selectType=='燃气-储气罐'">
            <!--<el-table-column property="carId" label="主键"></el-table-column>-->
            <el-table-column v-for="(item, index) in tableColumns3" :key="'type3.' + index + '.'+item.filedProp" :width="160"
                             :prop="item.filedProp" :label="item.filedName">
              <template #default="scope">
                <span v-if="!scope.row.isEdit">
                  {{ scope.row.dictItemNameObj[item.filedProp] }}
                </span>
                <el-form-item v-else :prop="'tableData.' + scope.$index + '.' + item.filedProp" :rules="tableDataForm.rules3[item.filedProp]">
                  <el-select v-if="item.filedType=='select'" v-model="scope.row[item.filedProp]" @change="(value) => onChangeSelect(value,item.filedProp,scope.row)"
                             :disabled="item.readonly=='readonly'" placeholder="请选择" clearable>
                    <el-option v-for="item in getDictArray(scope.row,item.filedProp,item.filedName,selectType)" :key="item.code" :label="item.name"
                               :value="item.code">
                    </el-option>
                  </el-select>
                  <el-input v-else-if="item.readonly=='readonly'" v-model.trim="scope.row.dictItemNameObj[item.filedProp]" :disabled="item.readonly=='readonly'"></el-input>
                  <el-input v-else v-model.trim="scope.row[item.filedProp]"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </template>
          <el-table-column v-if="isManage" label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button type="text" size="small" @click="handleModify(scope.$index, scope.row)"
                         :disabled="scope.row.createUser!=currentUserId">
                {{ scope.row.isEdit ? '应用' : '修改' }}
              </el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.$index, scope.row)"
                         :disabled="scope.row.createUser!=currentUserId">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <!--分页显示-->
    <div class="new-queryTableDiv-page">
      <el-pagination v-show="totalCount>0"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @current-change="handleCurrentChange" @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { queryByPage,findById,getValueByDictCodeAndKey,getValidDictItemsByDictCode,updateData,deleteData } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
import {reactive, toRefs} from "vue";
import { getInfo } from '@/api/login';
import { getUserId } from "@/utils/auth";
import { ElMessage, ElMessageBox } from 'element-plus';
import { getProvince, getChildArea } from "@/api/system/division";

const props = defineProps({
  isManage: {
    type: Boolean,
    default: false
  },
  queryParams: {
    type: Object,
    default: {}
  },
  selectType: {
    type: String,
    default: ''
  },
  //根据id查询1条数据
  selectId: {
    type: String,
    default: ''
  },
  showTable: {
    type: Boolean,
    default: false
  },
  versionId: {
    type: String,
    default: ''
  },
});

const { proxy } = getCurrentInstance();
const loading = ref(false);
const dataTypeArray = ref(["重大工程历史震害", "水库大坝", "燃气-储气罐"]);
//分页显示表格数据
const currentPage = ref(1);//当前页码
const pageSize = ref(10);//每页显示数据数量
const totalCount = ref(0);//总数据数量
const multipleSelection = ref([]);//多选表格数据
const currentUserId = ref(null);//当前登录人ID
const provinceData = ref([]); //全部省
const allCityData = ref(new Map()); //全部市
const allCountyData = ref(new Map()); //全部区县
const showSelectId = ref(false);//是否显示1条数据详情

//验证是否正整数（非必填）
const isIntegerNotMust = (rule, value, callback) => {
  if (value == '' || value == undefined || value == null) {
    callback();
  } else if (isNaN(Number(value))) {
    callback(new Error('请输入正整数'));
  } else if (Number(value) < 0) {
    callback(new Error('请输入正整数'));
  } else if (Number(value).toString().indexOf(".")!=-1) {
    callback(new Error('请输入正整数'));
  } else {
    callback();
  }
}

//验证是否正数（非必填）
const isNumberNotMust = (rule, value, callback) => {
  if (value == '' || value == undefined || value == null) {
    callback();
  } else if (isNaN(Number(value))) {
    callback(new Error('请输入正数'));
  } else if (Number(value) < 0) {
    callback(new Error('请输入正数'));
  } else {
    callback();
  }
}

//验证是否yyyy年份（非必填）
const isYearNotMust = (rule, value, callback) => {
  if (value == '' || value == undefined || value == null) {
    callback();
  } else if (isNaN(Number(value))) {
    callback(new Error('请输入yyyy格式如2022'));
  } else if (value.toString().length!=4) {
    callback(new Error('请输入yyyy格式如2022'));
  } else if (value.toString().indexOf(".")!=-1) {
    callback(new Error('请输入yyyy格式如2022'));
  } else {
    callback();
  }
}

// 验证经度（非必填）
const validateLon = (rule, value, callback) => {
  let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g; // 整数或小数
  if (!value) {
    callback()
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确数值'))
  } else if (value > 180) {
    callback(new Error('经度必须小于180'))
  } else if (value < 0) {
    callback(new Error('经度必须大于0'))
  } else if (value.indexOf(".") != -1 && value.split(".")[1].length > 15) {
    callback(new Error('最多保留15位小数'));
  } else {
    callback();
  }
}

// 验证纬度（非必填）
const validateLat = (rule, value, callback) => {
  let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g; // 整数或小数
  if (!value) {
    callback()
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确数值'))
  } else if (value > 90) {
    callback(new Error('纬度必须小于90'))
  } else if (value < 0) {
    callback(new Error('纬度必须大于0'))
  } else if (value.indexOf(".") != -1 && value.split(".")[1].length > 15) {
    callback(new Error('最多保留15位小数'));
  } else {
    callback();
  }
}

const data = reactive({
  params: {
    province: "",
    city: "",
    county: "",
    type: "",//数据类型
    page:1,
    rows:10,
  },
  tableDataForm: {
    tableData: [],//表格数据
    //通用字段
    rules0: {
      province: [{required: false, message: '请输入省', trigger: 'blur'},],
      city: [{required: false, message: '请输入市', trigger: 'blur'},],
      county: [{required: false, message: '请输入区县', trigger: 'blur'},],
      extends1: [{required: false, message: '请输入extends1', trigger: 'blur'},],
      extends2: [{required: false, message: '请输入extends2', trigger: 'blur'},],
      extends3: [{required: false, message: '请输入extends3', trigger: 'blur'},],
      extends4: [{required: false, message: '请输入extends4', trigger: 'blur'},],
      extends5: [{required: false, message: '请输入extends5', trigger: 'blur'},],
      extends6: [{required: false, message: '请输入extends6', trigger: 'blur'},],
      extends7: [{required: false, message: '请输入extends7', trigger: 'blur'},],
      extends8: [{required: false, message: '请输入extends8', trigger: 'blur'},],
      extends9: [{required: false, message: '请输入extends9', trigger: 'blur'},],
      extends10: [{required: false, message: '请输入extends10', trigger: 'blur'},],
    },
    //重大工程历史震害
    rules1: {
      seismName: [{required: true, message: '请输入地震名称', trigger: 'blur'},],
      seismDate: [{required: true, message: '请输入发生日期', trigger: 'blur'},],
      seismTime: [{required: true, message: '请输入发生时间', trigger: 'blur'},],
      magnitude: [{required: true, message: '请输入震级', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      projectType: [{required: true, message: '请输入重大工程类型', trigger: 'change'},],
      fortification: [{required: true, message: '请输入设防情况', trigger: 'change'},],
      year: [{required: true, message: '请输入年代', trigger: 'change'}],//,{trigger: 'blur',validator: isYearNotMust}
      // defenseSituation: [{required: true, message: '请输入地震动参数（烈度）', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      // destructiveState: [{required: true, message: '请输入破坏状态', trigger: 'blur'},],
    },
    //水库大坝
    rules2: {
      crName: [{required: true, message: '请输入水坝名称', trigger: 'blur'},],
      location: [{required: true, message: '请输入水坝地点', trigger: 'blur'},],
      longitude: [{required: true, message: '请输入经度', trigger: 'blur'},{trigger: 'blur',validator: validateLon}],
      latitude: [{required: true, message: '请输入纬度', trigger: 'blur'},{trigger: 'blur',validator: validateLat}],
      capacity: [{required: true, message: '请输入库容（立方米）', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      year: [{required: true, message: '请输入建造年代', trigger: 'blur'},{trigger: 'blur',validator: isYearNotMust}],
      damLength: [{required: true, message: '请输入坝长', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      damHeight: [{required: true, message: '请输入坝高', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      topWidth: [{required: true, message: '请输入顶宽', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      structureType: [{required: true, message: '请输入结构类型', trigger: 'change'},],
      type: [{required: true, message: '请输入水坝类型', trigger: 'change'},],
      intensity: [{required: true, message: '请输入设防烈度', trigger: 'change'},],
      site: [{required: true, message: '请输入位置', trigger: 'change'},],
      space: [{required: true, message: '请输入场地', trigger: 'change'},],
      filling: [{required: true, message: '请输入填料', trigger: 'change'},],
      damFoundation: [{required: true, message: '请输入坝基', trigger: 'change'},],
      maintenanceStatus: [{required: true, message: '请输入维护现状', trigger: 'change'},],
    },
    //燃气-储气罐
    rules3: {
      id: [{required: false, message: '请输入储气罐编码', trigger: 'blur'},],
      carName: [{required: true, message: '请输入储气罐名称', trigger: 'blur'},],
      longitude: [{required: true, message: '请输入经度', trigger: 'blur'},{trigger: 'blur',validator: validateLon}],
      latitude: [{required: true, message: '请输入纬度', trigger: 'blur'},{trigger: 'blur',validator: validateLat}],
      style: [{required: true, message: '请输入型号', trigger: 'blur'},],
      capacity: [{required: true, message: '请输入公称容积', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      pressure: [{required: true, message: '请输入工作压力', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      innerDiameter: [{required: true, message: '请输入筒体内径', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      height: [{required: true, message: '请输入筒体高度', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      thickness: [{required: true, message: '请输入筒体、封头壁厚', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      weight: [{required: true, message: '请输入参考重量', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      material: [{required: true, message: '请输入结构材料', trigger: 'blur'},],
      railLength: [{required: true, message: '请输入导轨长度', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      railHeight: [{required: true, message: '请输入导轨高度', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      railThickness: [{required: true, message: '请输入导轨中腹厚度', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      baseType: [{required: true, message: '请输入基础形式', trigger: 'blur'},],
      materialType: [{required: false, message: '请输入材料型号', trigger: 'blur'},],
      elasticModulus: [{required: false, message: '请输入弹性模量', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      yieldStress: [{required: false, message: '请输入屈服应力', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      permissibleStress: [{required: false, message: '请输入许用应力', trigger: 'blur'},{trigger: 'blur',validator: isNumberNotMust}],
      site: [{required: false, message: '请输入场地类别', trigger: 'change'},],
      liquefaction6: [{required: false, message: '请输入6度时液化程度', trigger: 'change'},],
      liquefaction7: [{required: false, message: '请输入7度时液化程度', trigger: 'change'},],
      liquefactio8: [{required: false, message: '请输入8度时液化程度', trigger: 'change'},],
      liquefaction9: [{required: false, message: '请输入9度时液化程度', trigger: 'change'},],
      seismicSubsidence6: [{required: false, message: '请输入6度时震陷程度', trigger: 'change'},],
      seismicSubsidence7: [{required: false, message: '请输入7度时震陷程度', trigger: 'change'},],
      seismicSubsidence8: [{required: false, message: '请输入8度时震陷程度', trigger: 'change'},],
      seismicSubsidence9: [{required: false, message: '请输入9度时震陷程度', trigger: 'change'},],
      year: [{required: false, message: '请输入建设年代', trigger: 'blur'},{trigger: 'blur',validator: isYearNotMust}],
      intensity: [{required: false, message: '请输入设防烈度', trigger: 'change'},],
    },
  },
});
const {
  params,tableDataForm,
} = toRefs(data);

//获取查询数据类型
function getSelectTypeNumStr(){
  let type = dataTypeArray.value.indexOf(props.selectType) + 1;
  let selectType = props.selectType;
  if(selectType=="重大工程历史震害"){
    type = "16";//test
  }else if(selectType=="水库大坝"){
    type = "17";//test
  }

  return type;
}

//查询
watch(() => props.showTable, val => {
  if(val){
    params.value.province = props.queryParams.province;
    params.value.city = props.queryParams.city;
    params.value.county = props.queryParams.county;
    //获取查询数据类型
    let type = getSelectTypeNumStr();
    params.value.type = type;
    //查询数据
    queryTableData();
  }
},{ deep: true, immediate: true });

const emits = defineEmits(['closeTableDiv']);
//关闭
const closeTableDiv = ()=>{
  emits("closeTableDiv");
}

//分页
const handleSizeChange = (val) => {
  // 改变每页显示的条数
  pageSize.value = val;
  // 注意：在改变每页显示的条数时，要将页码显示到第一页
  currentPage.value = 1;
  queryTableData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryTableData();
};

//查询数据
function queryTableData(){
  let id = props.selectId;
  if(id==="" || id==null){//查询全部
    showSelectId.value = false;
    //分页查询数据
    queryTableDataByPage();
  }else{//根据ID查询
    showSelectId.value = true;
    queryTableDataById();
  }
}

//分页查询数据
function queryTableDataByPage(){
  params.value.page = currentPage.value;
  params.value.rows = pageSize.value;
  params.value.versionId = props.versionId;
  let selectType = props.selectType;
  let typeIndex = dataTypeArray.value.indexOf(selectType);
  let allTableColumnsArray = allTableColumns.value;
  let tableColumnsArray = allTableColumnsArray[typeIndex];
  //数据查询
  loading.value = true;
  //分页查询
  queryByPage(params.value).then((response) => {
    nextTick(() => {
      let result = response.data.rows;
      if(result && result.length>0){
        for(let i=0;i<result.length;i++){
          result[i].isEdit = false;//是否编辑状态
          //创建字典值对象
          result[i].dictItemNameObj = Object.create(null);
          for(let j=0;j<tableColumnsArray.length;j++){
            let filedProp = tableColumnsArray[j].filedProp;
            let filedName = tableColumnsArray[j].filedName;
            /*let filedValue = result[i][filedProp];
            if(filedValue && typeof filedValue==="string"){
              let trimValue = filedValue.trim();//去除两侧空格
              result[i][filedProp] = trimValue;
            }*/
            let dictItemName = dictChange(i,result[i],filedProp,filedName,selectType);
            //获取字典值
            result[i].dictItemNameObj[filedProp] = dictItemName;
          }
          // console.log("result");
          // console.log(result);
          tableDataForm.value.tableData = result;
        }
      }else{
        tableDataForm.value.tableData = [];
      }
      totalCount.value = response.data.total;
      loading.value = false;
      multipleSelection.value = [];//清空多选
    });
  }).catch(err => {
    console.log(err);
    totalCount.value = 0;
    tableDataForm.value.tableData = [];
    multipleSelection.value = [];//清空多选
    loading.value = false;
  });
}

//根据ID查询数据
function queryTableDataById(){
  // console.log("根据ID查询数据");
  let id = props.selectId;
  //获取查询数据类型
  let type = getSelectTypeNumStr();
  let selectType = props.selectType;
  let typeIndex = dataTypeArray.value.indexOf(selectType);
  let allTableColumnsArray = allTableColumns.value;
  let tableColumnsArray = allTableColumnsArray[typeIndex];
  //数据查询
  loading.value = true;
  //查询
  findById(id,type).then((response) => {
    nextTick(() => {
      // console.log(response.data);
      let result = [];
      if(response.data){
        result = [response.data];
      }
      if(result && result.length>0){
        for(let i=0;i<result.length;i++){
          result[i].isEdit = false;//是否编辑状态
          //创建字典值对象
          result[i].dictItemNameObj = Object.create(null);
          for(let j=0;j<tableColumnsArray.length;j++){
            let filedProp = tableColumnsArray[j].filedProp;
            let filedName = tableColumnsArray[j].filedName;
            /*let filedValue = result[i][filedProp];
            if(filedValue && typeof filedValue==="string"){
              let trimValue = filedValue.trim();//去除两侧空格
              result[i][filedProp] = trimValue;
            }*/
            let dictItemName = dictChange(i,result[i],filedProp,filedName,selectType);
            //获取字典值
            result[i].dictItemNameObj[filedProp] = dictItemName;
          }
        }
        tableDataForm.value.tableData = result;
      }else{
        tableDataForm.value.tableData = [];
      }
      totalCount.value = response.data.total;
      loading.value = false;
      multipleSelection.value = [];//清空多选
    });
  }).catch(err => {
    console.log(err);
    totalCount.value = 0;
    tableDataForm.value.tableData = [];
    multipleSelection.value = [];//清空多选
    loading.value = false;
  });
}

// 转换时间
function getFormatTime(time) {
  if(time && time!==""){
    let d = new Date(time);
    let year = d.getFullYear();
    let month = d.getMonth() + 1;
    if(month<10) month = "0" + month;
    let date = d.getDate();
    if(date<10) date = "0" + date;
    let hours = d.getHours();
    if(hours<10) hours = "0" + hours;
    let minutes = d.getMinutes();
    if(minutes<10) minutes = "0" + minutes;
    let seconds = d.getSeconds();
    if(seconds<10) seconds = "0" + seconds;
    let newTime = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
    return newTime;
  }else{
    return "";
  }
}

//数据解析
const dictChange = (index, data, col, colName, dictName) => {
  if(col=="createUser" || col=="updateUser"){
    // 获取用户名
    return getUserInfo(index,data,col);
  }else if(col=="createTime" || col=="updateTime" || col=="occurrenceTime"){
    // 格式化时间
    return getFormatTime(data[col]);
  }else{
    let dictArr = getDictArray(data, col, colName, dictName);
    if (data[col]!=null && dictArr!=null && dictArr.length>0) {
      let code = data[col];
      /*if(code && typeof code==="string"){
        let trimValue = code.trim();//去除两侧空格
        code = trimValue;
      }*/
      for (let item of dictArr) {
        if (item.code == code) {
          //字典值
          return item.name;
        }
      }
    }
  }

  return data[col];
}

//字典表信息数组
const dictInfoArray = ref([
  {dictCode:"smxyhcd",dictName:"生命线-液化程度和震陷程度"},
  {dictCode:"smxsfqk",dictName:"生命线-设防烈度"},
  {dictCode:"smxcdlb",dictName:"生命线-场地类别"},
  {dictCode:"skdbjglx",dictName:"生命线-水库大坝-结构类型"},
  {dictCode:"skdbsblx",dictName:"生命线-水库大坝-水坝类型"},
  {dictCode:"skdbcd",dictName:"生命线-水库大坝-场地"},
  {dictCode:"skdbtl",dictName:"生命线-水库大坝-填料"},
  {dictCode:"skdbbj",dictName:"生命线-水库大坝-坝基"},
  {dictCode:"skdbwhxz",dictName:"生命线-水库大坝-维护现状"},
]);
//全部字典表数组
const allDictArray = ref([]);
//获取全部字典表
function getAllDictArray(){
  allDictArray.value = [];//清空
  let array = dictInfoArray.value;
  for(let i=0;i<array.length;i++){
    let dictCode = array[i].dictCode;
    //字典表查询
    getValidDictItems(dictCode);
  }
}

//字典表查询
function getValidDictItems(dictCode){
  //查询
  getValidDictItemsByDictCode(dictCode).then((response) => {
    nextTick(() => {
      let dictItems = response.data;
      let obj = {
        dictCode:dictCode,
        dictItems:dictItems
      };
      allDictArray.value.push(obj);
    });
  }).catch(err => {
    console.log(err);
  });
}

//字典项查询
function getDictValue(dictCode,key){
  //查询
  getValueByDictCodeAndKey(dictCode,key).then((response) => {
    nextTick(() => {
      // console.log(response.data);
    });
  }).catch(err => {
    console.log(err);
  });
}

//获取字典数组
function getDictArray(data, col, colName, dictName){
  let array = null;
  let dictCode = null;
  if(colName.indexOf("液化程度")!=-1 || colName.indexOf("震陷程度")!=-1){
    dictCode = "smxyhcd";
  }else if(colName=="场地类别" || colName=="场地土分类" || colName=="场地类型"){
    dictCode = "smxcdlb";
  }else if(colName=="设防烈度" || colName=="抗震设防烈度" || colName=="评价单元设防烈度" || colName=="设防标准" || colName=="设防情况"){
    dictCode = "smxsfqk";
  }
  if(dictName=="重大工程历史震害"){
    if(colName=="6度破坏状态" || colName=="7度破坏状态" || colName=="8度破坏状态" || colName=="9度破坏状态" || colName=="10度破坏状态" || colName=="11度破坏状态" || colName=="12度破坏状态"){
      array = [
        {code:"基本完好",name:"基本完好"},
        {code:"轻微破坏",name:"轻微破坏"},
        {code:"中等破坏",name:"中等破坏"},
        {code:"严重破坏",name:"严重破坏"},
        {code:"倒塌",name:"倒塌"},
      ];
      dictCode = null;
    }else if(colName == '年代') {
      array = [
        {code:"1978年以前",name:"1978年以前"},
        {code:"1978-1989年",name:"1978-1989年"},
        {code:"1989-2001年",name:"1989-2001年"},
        {code:"2001年以后",name:"2001年以后"},
      ];
      dictCode = null;
    }else if(colName == '重大工程类型') {
      array = [
        {code:"输油管线",name:"输油管线"},
        {code:"输气管线",name:"输气管线"},
        {code:"核电站",name:"核电站"},
        {code:"水库大坝",name:"水库大坝"},
      ];
      dictCode = null;
    }
  }else if(dictName=="水库大坝"){
    if(colName=="结构类型"){
      dictCode = "skdbjglx";
    }else if(colName=="水坝类型"){
      dictCode = "skdbsblx";
    }else if(colName=="场地"){
      dictCode = "skdbcd";
    }else if(colName=="填料"){
      dictCode = "skdbtl";
    }else if(colName=="坝基"){
      dictCode = "skdbbj";
    }else if(colName=="维护现状"){
      dictCode = "skdbwhxz";
    }else if(colName=="位置"){
      array = [
        {code:"上游",name:"上游"},
        {code:"中游",name:"中游"},
        {code:"下游",name:"下游"},
      ];
    }else if(colName=="设防烈度"){
      array = [
        {code:"无设防",name:"无设防"},
        {code:"6度设防",name:"6度设防"},
        {code:"7度设防",name:"7度设防"},
        {code:"9度设防",name:"9度设防"},
        {code:"10度设防",name:"10度设防"},
        {code:"加固",name:"加固"},
        {code:"不详",name:"不详"},
      ];
      dictCode = null;
    }
  }
  if(dictCode){
    //字典表
    let allArray = allDictArray.value;
    for(let i=0;i<allArray.length;i++){
      if(allArray[i].dictCode==dictCode){
        array = [];
        let dictItems = allArray[i].dictItems;
        for(let i=0;i<dictItems.length;i++){
          let obj = {
            code: dictItems[i].dictItemCode,
            name: dictItems[i].dictItemName,
          }
          array.push(obj);
        }
        break;
      }
    }
  }else{
    if(data.isEdit) {//编辑状态
      //省市县下拉选择
      if(colName=="省"){
        array = [];
        let provinceArray = provinceData.value;
        for(let i=0;i<provinceArray.length;i++){
          let obj = {
            code: provinceArray[i].name,
            name: provinceArray[i].name,
          }
          array.push(obj);
        }
      }else if(colName=="市"){
        array = [];
        let province = data["province"];
        //根据省获取市列表
        let cityArray = chooseProvince(province);
        for(let i=0;i<cityArray.length;i++){
          let obj = {
            code: cityArray[i].name,
            name: cityArray[i].name,
          }
          array.push(obj);
        }
      }else if(colName=="区县"){
        array = [];
        let province = data["province"];
        let city = data["city"];
        //根据省获取市列表
        let cityArray = chooseProvince(province);
        for(let i=0;i<cityArray.length;i++){
          if(cityArray[i].name==city){
            //根据市获取区县列表
            let countyArray = chooseCity(cityArray[i].id);
            for(let i=0;i<countyArray.length;i++){
              let obj = {
                code: countyArray[i].name,
                name: countyArray[i].name,
              }
              array.push(obj);
            }
            break;
          }
        }
      }
    }
  }
  return array;
}

//查询结果多选事件
function handleSelectionChange(val) {
  multipleSelection.value = val;
}

//删除选择的数据
function deleteSelectData(){
  let ids = "";
  let selectRows = multipleSelection.value;
  if(selectRows!=null && selectRows.length>0){
    if(selectRows.length>10){
      proxy.$modal.msgWarning("最多勾选10条数据进行删除!");
      return;
    }
    for(let i=0;i<selectRows.length;i++){
      if(ids!=""){
        ids += ",";
      }
      let uuid = getRowUuid(selectRows[i]);//根据数据类型获取主键id
      //主键
      if(uuid){
        ids += uuid;
      }
    }
    //删除事件
    deleteEvent(ids);
  }else{
    proxy.$modal.msgWarning("请勾选1条数据进行删除!");
  }
}

//根据数据类型获取主键id
function getRowUuid(row){
  let selectType = props.selectType;
  let uuid = null;
  if(row){
    if(selectType=='重大工程历史震害'){
      uuid = row.cmpId;
    }else if(selectType=='水库大坝'){
      uuid = row.crId;
    }else if(selectType=='燃气-储气罐'){
      uuid = row.carId;
    }
  }

  return uuid;
}

//通用字段
const tableColumns0 = ref([
  // { filedProp:"province", filedName:"省", filedType:"select" },
  // { filedProp:"city", filedName:"市", filedType:"select" },
  // { filedProp:"county", filedName:"区县", filedType:"select" },
  // { filedProp:"extends1", filedName:"extends1", filedType:"input" },
  // { filedProp:"extends2", filedName:"extends2", filedType:"input" },
  // { filedProp:"extends3", filedName:"extends3", filedType:"input" },
  // { filedProp:"extends4", filedName:"extends4", filedType:"input" },
  // { filedProp:"extends5", filedName:"extends5", filedType:"input" },
  // { filedProp:"extends6", filedName:"extends6", filedType:"input" },
  // { filedProp:"extends7", filedName:"extends7", filedType:"input" },
  // { filedProp:"extends8", filedName:"extends8", filedType:"input" },
  // { filedProp:"extends9", filedName:"extends9", filedType:"input" },
  // { filedProp:"extends10", filedName:"extends10", filedType:"input" },
  { filedProp:"createUser", filedName:"创建人", filedType:"input", readonly:"readonly" },
  { filedProp:"createTime", filedName:"创建时间", filedType:"input", readonly:"readonly" },
  { filedProp:"updateUser", filedName:"修改人", filedType:"input", readonly:"readonly" },
  { filedProp:"updateTime", filedName:"修改时间", filedType:"input", readonly:"readonly" },
]);

//重大工程历史震害
const tableColumns1 = ref([
  // { filedProp:"id", filedName:"序号", filedType:"input" },
  { filedProp:"seismName", filedName:"地震名称", filedType:"input" },
  { filedProp:"seismDate", filedName:"发生日期", filedType:"data" },
  { filedProp:"seismTime", filedName:"发生时间", filedType:"time" },
  { filedProp:"magnitude", filedName:"震级", filedType:"input" },
  { filedProp:"projectType", filedName:"重大工程类型", filedType:"select" },
  { filedProp:"fortification", filedName:"设防情况", filedType:"select" },
  { filedProp:"year", filedName:"年代", filedType:"select" },
  { filedProp:"destructive6State", filedName:"6度破坏状态", filedType:"select" },
  { filedProp:"destructive7State", filedName:"7度破坏状态", filedType:"select" },
  { filedProp:"destructive8State", filedName:"8度破坏状态", filedType:"select" },
  { filedProp:"destructive9State", filedName:"9度破坏状态", filedType:"select" },
  { filedProp:"destructive10State", filedName:"10度破坏状态", filedType:"select" },
  { filedProp:"destructive11State", filedName:"11度破坏状态", filedType:"select" },
  { filedProp:"destructive12State", filedName:"12度破坏状态", filedType:"select" },
  ...tableColumns0.value
]);

//水库大坝
const tableColumns2 = ref([
  { filedProp:"crName", filedName:"水坝名称", filedType:"input" },
  { filedProp:"location", filedName:"水坝地点", filedType:"input" },
  { filedProp:"longitude", filedName:"经度", filedType:"number", readonly:"readonly" },
  { filedProp:"latitude", filedName:"纬度", filedType:"number", readonly:"readonly" },
  { filedProp:"capacity", filedName:"库容（立方米）", filedType:"number" },
  { filedProp:"year", filedName:"建造年代", filedType:"input" },
  { filedProp:"damLength", filedName:"坝长", filedType:"number" },
  { filedProp:"damHeight", filedName:"坝高", filedType:"number" },
  { filedProp:"topWidth", filedName:"顶宽", filedType:"number" },
  { filedProp:"structureType", filedName:"结构类型", filedType:"select" },
  { filedProp:"type", filedName:"水坝类型", filedType:"select" },
  { filedProp:"intensity", filedName:"设防烈度", filedType:"select" },
  { filedProp:"site", filedName:"位置", filedType:"select" },
  { filedProp:"space", filedName:"场地", filedType:"select" },
  { filedProp:"filling", filedName:"填料", filedType:"select" },
  { filedProp:"damFoundation", filedName:"坝基", filedType:"select" },
  { filedProp:"maintenanceStatus", filedName:"维护现状", filedType:"select" },
  ...tableColumns0.value
]);

//燃气-储气罐
const tableColumns3 = ref([
  { filedProp:"id", filedName:"储气罐编码", filedType:"input" },
  { filedProp:"carName", filedName:"储气罐名称", filedType:"input" },
  { filedProp:"longitude", filedName:"经度", filedType:"number", readonly:"readonly" },
  { filedProp:"latitude", filedName:"纬度", filedType:"number", readonly:"readonly" },
  { filedProp:"style", filedName:"型号", filedType:"input" },
  { filedProp:"capacity", filedName:"公称容积", filedType:"number" },
  { filedProp:"pressure", filedName:"工作压力", filedType:"number" },
  { filedProp:"innerDiameter", filedName:"筒体内径", filedType:"number" },
  { filedProp:"height", filedName:"筒体高度", filedType:"number" },
  { filedProp:"thickness", filedName:"筒体、封头壁厚", filedType:"number" },
  { filedProp:"weight", filedName:"参考重量", filedType:"number" },
  { filedProp:"material", filedName:"结构材料", filedType:"input" },
  { filedProp:"railLength", filedName:"导轨长度", filedType:"number" },
  { filedProp:"railHeight", filedName:"导轨高度", filedType:"number" },
  { filedProp:"railThickness", filedName:"导轨中腹厚度", filedType:"number" },
  { filedProp:"baseType", filedName:"基础形式", filedType:"input" },
  { filedProp:"materialType", filedName:"材料型号", filedType:"input" },
  { filedProp:"elasticModulus", filedName:"弹性模量", filedType:"number" },
  { filedProp:"yieldStress", filedName:"屈服应力", filedType:"number" },
  { filedProp:"permissibleStress", filedName:"许用应力", filedType:"number" },
  { filedProp:"site", filedName:"场地类别", filedType:"select" },
  { filedProp:"liquefaction6", filedName:"6度时液化程度", filedType:"select" },
  { filedProp:"liquefaction7", filedName:"7度时液化程度", filedType:"select" },
  { filedProp:"liquefactio8", filedName:"8度时液化程度", filedType:"select" },
  { filedProp:"liquefaction9", filedName:"9度时液化程度", filedType:"select" },
  { filedProp:"seismicSubsidence6", filedName:"6度时震陷程度", filedType:"select" },
  { filedProp:"seismicSubsidence7", filedName:"7度时震陷程度", filedType:"select" },
  { filedProp:"seismicSubsidence8", filedName:"8度时震陷程度", filedType:"select" },
  { filedProp:"seismicSubsidence9", filedName:"9度时震陷程度", filedType:"select" },
  { filedProp:"year", filedName:"建设年代", filedType:"input" },
  { filedProp:"intensity", filedName:"设防烈度", filedType:"select" },
  ...tableColumns0.value
]);

//全部表格字段信息数组
const allTableColumns = ref([
  tableColumns1.value,tableColumns2.value,tableColumns3.value
]);

//删除事件
function deleteEvent(ids){
  if(ids && ids!==""){
    proxy.$modal
        .confirm("请确认是否要删除？",)
        .then(function () {
          //获取查询数据类型
          let type = getSelectTypeNumStr();
          let formMap = new Map();
          formMap.set("ids",ids);
          //map转obj
          let obj = Object.create(null);
          for (let[k,v] of formMap) {
            obj[k] = v;
          }
          let data = {
            map: obj,
            type: type
          }
          //删除数据
          return deleteData(data);
        })
        .then(() => {
          //查询数据
          queryTableData();
          proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
  }
}

//删除
const handleDelete = (index, row) => {
  let uuid = getRowUuid(row);//根据数据类型获取主键id
  //删除事件
  deleteEvent(uuid);
}

//修改
const handleModify = (index, row) => {
  if(row.isEdit){//保存修改
    //获取查询数据类型
    let type = getSelectTypeNumStr();
    let formMap = new Map();
    formMap.set(type,row);
    //map转obj
    let obj= Object.create(null);
    for (let[k,v] of formMap) {
      obj[k] = v;
    }
    let form = {
      map: obj,
      // type: type
    }
    // console.log(form);
    //校验
    proxy.$refs['formTable'].validate((valid, fields) => {
      if (valid) {
        //更新数据
        updateData(obj).then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: '修改成功!'
            });
            row.isEdit = false;
            //查询数据
            queryTableData();
          }
        }).catch(err => {
          console.log(err);
        });
      } else {
        proxy.$modal.msgWarning("校验失败!");
        proxy.$refs['formTable'].scrollToField(Object.keys(fields)[0]);
      }
    });
  }else{//开启修改
    row.isEdit = true;
  }
}

//下拉框选择事件
const onChangeSelect = (value,filedProp,row)=>{
  //省市县下拉选择事件
  if(filedProp=="province"){
    row["city"] = "";
    row["county"] = "";
  }else if(filedProp=="city"){
    row["county"] = "";
  }else if(filedProp=="county"){

  }
}

/** 获取省列表 */
function getProvinceData() {
  provinceData.value = [];
  allCityData.value = new Map();
  allCountyData.value = new Map();
  //全部省
  getProvince().then((response) => {
    let provinceArray = response.data;
    provinceData.value = provinceArray;
    for(let i=0;i<provinceArray.length;i++){
      //获取市列表
      getCityData(provinceArray[i].id);
    }
  });
}

//获取市列表
function getCityData(provinceId) {
  getChildArea(provinceId).then(response => {
    let cityArray = response.data;
    allCityData.value.set(provinceId,cityArray);
    for(let i=0;i<cityArray.length;i++){
      //获取区县列表
      getCountyData(cityArray[i].id);
    }
  });
}

//获取区县列表
function getCountyData(cityId) {
  getChildArea(cityId).then(response => {
    let countyData = response.data;
    allCountyData.value.set(cityId,countyData);
  });
}

//根据省名获取省ID
function getProvinceId(name) {
  let provinceId = null;
  let provinceArray = provinceData.value;
  for(let i=0;i<provinceArray.length;i++) {
    if (provinceArray[i].name == name) {
      provinceId = provinceArray[i].id;
      break;
    }
  }
  return provinceId;
}

//根据省获取市列表
const chooseProvince = (name) => {
  let cityData = [];
  let provinceId = getProvinceId(name);//根据省名获取省ID
  if(provinceId){
    cityData = allCityData.value.get(provinceId);
  }
  return cityData;
}
//根据市获取区县列表
const chooseCity = (cityId) => {
  let areaData = [];
  if(cityId){
    areaData = allCountyData.value.get(cityId);
  }
  return areaData;
}

//当前登录人ID
function getCurrentUserId(){
  let userId = getUserId();
  currentUserId.value = userId;
}

const userInfoMap = ref(new Map());//用户信息Map
// 获取用户名
function getUserInfo(index,data, col){
  let userName = "";
  let userId = data[col];
  if(userId){
    userName = userInfoMap.value.get(userId);
    if(userName==undefined){
      userName = "";
      //用户信息Map
      userInfoMap.value.set(userId,userName);
      //获取用户信息
      getInfo(userId).then(response => {
        userName = response.user.userName;
        //用户信息Map
        userInfoMap.value.set(userId,userName);
        //遍历更新用户数据
        let tableData = tableDataForm.value.tableData;
        for(let i=0;i<tableData.length;i++){
          if(tableData[i].createUser==userId){
            //设置用户名
            tableDataForm.value.tableData[i].dictItemNameObj["createUser"] = userName;
          }
          if(tableData[i].updateUser==userId){
            //设置用户名
            tableDataForm.value.tableData[i].dictItemNameObj["updateUser"] = userName;
          }
        }
      });
    }
  }

  return userName;
}

//获取省列表
getProvinceData();
//当前登录人ID
getCurrentUserId();
//获取全部字典表
getAllDictArray();

</script>

<style lang="scss" scoped>
.min-Table{
  height:200px;
}
.max-Table{
  height:90%;
}
//下方查看详情面板
.new-queryResultDiv {
  position: absolute;
  left:0px;
  right:0px;
  bottom:0px;
  /*height:140px;*/
  height:90%;
  background:#fff;
  z-index: 10;
  border: 1px solid #e4e7ed;
}
.new-queryTableBtn {
  position: absolute;
  left:0px;
  right:0px;
  top:0px;
  height:50px;
  padding:10px;
}
.new-queryTableSpan{
  position: relative;
  top: -32px;
  width: 100%;
  text-align: center;
  font-weight: bold;
  font-size: 18px;
  color: #107ce5;
  display: inline-block;
  line-height: 32px;
  z-index: -1;
}
.new-queryTableDiv {
  position: absolute;
  left:0px;
  right:0px;
  top:50px;
  bottom:50px;
}
.new-queryTableDiv-page {
  position: absolute;
  left:0px;
  right:0px;
  bottom:0px;
  height:50px;
  padding: 8px;
}

:deep(.el-form-item--default) {
  padding-top: 20px;
}
</style>